﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Windows.Forms;
using System.Reflection;

namespace CXJ.BLL
{
    public class UIProcess
    {
        private static UIProcess _Instance = null;
        public static UIProcess Instance
        {
            get
            {
                if (_Instance == null) { _Instance = new UIProcess(); }
                return _Instance;
            }
        }

        public void SetEntityValue(Form form, Interface.IBaseEntity entity, string command)
        {
            Type type = entity.GetType();
            foreach (PropertyInfo item in type.GetProperties())
            {
                if (!CheckIsColumn(item)) continue;
                string itemName = item.Name;
                Control[] controls = form.Controls.Find(command + itemName, true);
                if (controls == null || controls.Length < 1)
                {
                    continue;
                }
                item.SetValue(entity, GetControlValue(controls[0]), null);
            }
        }
        private object GetControlValue(Control control)
        {
            Type type = control.GetType();
            object resultObj = null;
            if (control is TextBox)
            {
                resultObj = control.Text;
            }
            return resultObj;
        }

        public bool CheckIsColumn(System.Reflection.PropertyInfo item)
        {
            try
            {
                object[] objs = item.GetCustomAttributes(typeof(CXJ.Libiary.DBColumnAttribue), true);
                if (objs.Length == 0) return false;
                CXJ.Libiary.DBColumnAttribue pAttribute = objs[0] as CXJ.Libiary.DBColumnAttribue;
                return pAttribute.IsDBColumn;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
